package controller

import (
	"encoding/json"
	"git.oschina.net/goweb/model"
	"net/http"
	"strings"
)

type Result struct {
	Ret    int
	Reason string
	Data   interface{}
}

type AjaxController struct{}

func (this *AjaxController) AjaxAction(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Content-Type", "application/json; charset=utf-8")
	err := r.ParseForm()

	if err != nil {
		OutputJson(w, 0, "参数错误", nil)
		return
	}

	username := strings.TrimSpace(r.PostFormValue("admin_name"))
	password := strings.TrimSpace(r.PostFormValue("admin_pass"))

	if username == "" || password == "" {
		OutputJson(w, 0, "用户名或密码为空", nil)
		return
	}

	user := model.User{UserName: username, Password: password}
	res := model.CheckUser(user)

	if res {
		cookie := http.Cookie{Name: "admin_name", Value: user.UserName, Path: "/"}
		http.SetCookie(w, &cookie)
		OutputJson(w, 1, "已成功登录", nil)
	} else {
		OutputJson(w, 0, "用户名或密码错误", nil)
	}
}

func OutputJson(w http.ResponseWriter, ret int, reason string, i interface{}) {
	out := &Result{ret, reason, i}
	b, err := json.Marshal(out)
	if err != nil {
		return
	}
	w.Write(b)
}
